package com.cryptape.cita_wallet.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cryptape.cita_wallet.CytonApplication;
import com.cryptape.cita_wallet.bean.LightNodeBean;
import com.cryptape.cita_wallet.bean.MyMIDBean;
import com.cryptape.cita_wallet.item.Wallet;
import com.cryptape.cita_wallet.net.callback.CommonCallback;
import com.cryptape.cita_wallet.net.request.HttpRequestMode;
import com.cryptape.cita_wallet.net.response.BaseResponse;
import com.cryptape.cita_wallet.service.http.TokenService;
import com.cryptape.cita_wallet.service.http.WalletService;
import com.cryptape.cita_wallet.util.Blockies;
import com.cryptape.cita_wallet.util.RSAUtils;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.cryptape.cita_wallet.util.permission.PermissionUtil;
import com.cryptape.cita_wallet.util.permission.RuntimeRationale;
import com.cryptape.cita_wallet.util.qrcode.CodeUtils;
import com.cryptape.cita_wallet.view.CompressEditText;
import com.cryptape.cita_wallet.view.TitleBar;
import com.cryptape.cita_wallet.view.button.CommonButton;
import com.cryptape.cita_wallet.view.dialog.TransferDialog;
import com.google.gson.Gson;
import com.mangoworld.android.R;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;

import static com.cryptape.cita_wallet.activity.MainActivity.REQUEST_CODE_SCAN;

public class NewActivateActivity extends NBaseActivity {

    private TitleBar titleBar;
    private CircleImageView photoImage;
    private TextView walletAddressText, walletNameText;
    private ImageView scanImage;
    private CompressEditText ct_invite;
    private CommonButton nextActionButton;

    private Wallet mWallet;
    private TransferDialog transferDialog;
    private ProgressBar progressBar;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_activate;
    }

    @Override
    protected void initView() {
        scanImage = findViewById(R.id.transfer_address_scan);
        nextActionButton = findViewById(R.id.next_action_button);
        walletAddressText = findViewById(R.id.wallet_address);
        walletNameText = findViewById(R.id.wallet_name);
        photoImage = findViewById(R.id.wallet_photo);
        titleBar = findViewById(R.id.title);
        ct_invite = findViewById(R.id.ct_invite);
    }

    @Override
    protected void initData() {
        mWallet = DBWalletUtil.getCurrentWallet(this);
        walletAddressText.setText(mWallet.address);
        walletNameText.setText(mWallet.name);
        photoImage.setImageBitmap(Blockies.createIcon(mWallet.address));
        isFindMIDBinding();
    }

    @Override
    protected void initAction() {
        scanImage.setOnClickListener((view) -> {
            AndPermission.with(mActivity)
                    .runtime().permission(Permission.Group.CAMERA)
                    .rationale(new RuntimeRationale())
                    .onGranted(permissions -> {
                        Intent intent = new Intent(mActivity, QrCodeActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    })
                    .onDenied(permissions -> PermissionUtil.showSettingDialog(mActivity, permissions))
                    .start();
        });

        nextActionButton.setOnClickListener(v -> {
            String pMidCode = ct_invite.getText();
            if (TextUtils.isEmpty(pMidCode)) {
                Toast.makeText(mActivity, getString(R.string.invitation_code_no_empty), Toast.LENGTH_LONG).show();
            } else {
                gotoConfirmTransferViewExec(pMidCode);
            }
        });
    }

    private void gotoConfirmTransferViewExec(String pMid) {
        if (isFastDoubleClick()) return;
        transferDialog = new TransferDialog(this, (password, progressBar) -> {
            this.progressBar = progressBar;
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(mActivity, R.string.password_not_null, Toast.LENGTH_SHORT).show();
            } else if (!WalletService.checkPassword(mActivity, password, mWallet)) {
                Toast.makeText(mActivity, R.string.password_fail, Toast.LENGTH_SHORT).show();
            } else {
                transferDialog.setButtonClickAble(false);
                progressBar.setVisibility(View.VISIBLE);
                bindMid(pMid);
            }
        });
        transferDialog.viewPager.setCurrentItem(1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCAN:
                if (null == data) return;
                Bundle bundle = data.getExtras();
                if (bundle == null) return;
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
//                    switch (bundle.getInt(CodeUtils.STRING_TYPE)) {
//                        case CodeUtils.STRING_ADDRESS:
//                            String result = bundle.getString(CodeUtils.RESULT_STRING);
//                            ct_invite.setText(result);
//                            break;
//                        default:
//                            Toast.makeText(this, R.string.address_error,
//                                    Toast.LENGTH_LONG).show();
//                            break;
//                    }
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    ct_invite.setText(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(NewActivateActivity.this, R.string.qrcode_handle_fail,
                            Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void bindMid(String pMid) {
        try {
            String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            params.put("parentMid", pMid);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.bindMid(NewActivateActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    transferDialog.dismiss();
                    progressBar.setVisibility(View.GONE);
                    MyMIDBean dataBean = (MyMIDBean) data;
                    if (dataBean != null) {
                        String mid = dataBean.getLnvitationCode();
                        CytonApplication.getInstance().MIDCode = mid;
                        finish();
                    }

                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    transferDialog.dismiss();
                    progressBar.setVisibility(View.GONE);
                    ToastUtils.showShort(msg);
                }
            });
        } catch (
                Exception e) {
            e.printStackTrace();
        }

    }

    private void isFindMIDBinding() {
        try {
            String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            params.put("type", "0");
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.isFindMIDBinding(NewActivateActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    if (ObjectUtils.isNotEmpty(data)) {
                        BaseResponse baseResponse = (BaseResponse) data;
                        if (baseResponse.getResult() == 0) {
                            nextActionButton.setClickAble(true);
                        } else {
                            nextActionButton.setClickAble(false);
                            ToastUtils.showLong(baseResponse.getMessage());
                        }
                    }
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    ToastUtils.showShort(msg);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
